package com.ruicar.afs.cloud.account.common.component;

import com.ruicar.afs.cloud.account.common.send.VoucherSendService;
import com.ruicar.afs.cloud.common.core.service.ServiceInfo;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import com.ruicar.afs.cloud.common.data.lock.anno.Lock;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@AllArgsConstructor
public class VoucherSendPublishComponent implements ApplicationListener<ApplicationReadyEvent> {
    private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
    private final VoucherSendService voucherSendService;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        schedule();
    }

    @Lock(keyConstant = ":lock-afs-voucher-Assembly-publish", keys = {"#serviceName"})
    public void publishVouchers(String serviceName) {
        try{
            voucherSendService.voucherInfoSend();
        } catch (Throwable e) {
            log.error("凭证发送异常", e);
        }
    }

    private void schedule() {
        //每10s 检测发布处理一次凭证取值
      EXECUTOR_SERVICE.scheduleWithFixedDelay(() -> {
            SpringContextHolder.getBean(VoucherSendPublishComponent.class).publishVouchers(ServiceInfo.getServiceName()+9);
        }, 2, 10, TimeUnit.SECONDS);

    }
}
